package com.zlp.mall.search.controller;

import com.alibaba.fastjson.JSON;
import com.zlp.mall.common.api.Pager;
import com.zlp.mall.search.domain.Googs;
import com.zlp.mall.search.repository.GoodsRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequiredArgsConstructor
public class ElasticsearchController {

    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 创建 Goods 文档对象
     */
    @GetMapping("createIndex")
    public boolean createIndex() {
        boolean result = elasticsearchRestTemplate.createIndex(Googs.class);
        return result;
    }

    /**
     * 删除索引
     */
    @GetMapping("testDeleteIndex")
    public boolean testDeleteIndex() {
        boolean result = elasticsearchRestTemplate.deleteIndex(Googs.class);
        return result;
    }

    /**
     * 高亮查询
     *
     * @date: 2021/11/3 15:34
     * @return: boolean
     */
    @GetMapping("hightLightSearch")
    public Pager hightLightSearch(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "0") Integer pageNum,
            @RequestParam(required = false, defaultValue = "5") Integer pageSize
    ) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        Page page;
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        queryBuilder.withQuery(QueryBuilders.matchQuery("title", keyword));
        // 高亮查询
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color=\"red\">");
        highlightBuilder.postTags("</font>");
        highlightBuilder.highlighterType("unified");
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//多次段高亮需要设置为false
        queryBuilder.withHighlightBuilder(highlightBuilder);

        NativeSearchQuery build = queryBuilder.build();
        // 搜索，获取结果
        SearchHits<Googs> searchHits = this.elasticsearchRestTemplate.search(build, Googs.class);
        if (searchHits.getTotalHits() <= 0) {
            return new Pager();
        }
        log.info("DSL:{}", build.getQuery().toString());
        List<Googs> searchProductList = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
        List<Map<String, List<String>>> highlightFields = searchHits.stream().map(SearchHit::getHighlightFields).collect(Collectors.toList());
        log.info("highlightFields={}", JSON.toJSONString(highlightFields));
        for (int i = 0; i < searchProductList.size(); i++) {
            Map<String, List<String>> fieldListMap = highlightFields.get(i);
            Googs googs = searchProductList.get(i);
            googs.setTitle(fieldListMap.get("title").get(0));
        }
        log.info("searchProductList={}", JSON.toJSONString(searchProductList));
        page = new PageImpl<>(searchProductList, pageable, searchHits.getTotalHits());
        return Pager.restPage(page);
    }


    public Integer getAppType(HttpServletRequest request) {

        String agent = request.getHeader("user-agent");
        log.info(agent);
        if (agent.contains("Android")) {
            return 1;
        }
        if (agent.contains("iPhone") || agent.contains("iPod") || agent.contains("iPad")) {
            return 2;
        }
        return 0;
    }

}